package org.shan.lf.sever.config;

import org.apache.commons.lang3.StringUtils;
import org.shan.lf.entity.UserAccount;
import org.shan.lf.service.UserService;
import org.shan.lf.sever.exception.LoginException;
import org.shan.security.app.authorize.AppAuthorizeManager;
import org.shan.security.app.authorize.MlnxOauthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by amanda.shan on 2019/6/20.
 */
@Component
public class SmartAppAuthorizeManager implements AppAuthorizeManager {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder encoder;

    @Override
    public MlnxOauthUser authenticate(Map<String, String> requestParameters, ClientDetails authenticatedClient) {

        String grantType = requestParameters.get(OAuth2Utils.GRANT_TYPE);

        // 刷新Token不需要添加用户名密码
        if (grantType.equals("refresh_token")){
            return null;
        }

        // 手机号登入
        String username = requestParameters.get("username");
        String password = requestParameters.get("password");
        String identity = requestParameters.get("identity");

        if (StringUtils.isEmpty(username)){
            throw new LoginException("用户名不能为空");
        }else if (StringUtils.isEmpty(identity)){
            throw new LoginException("身份标识不能为空");
        }
        else {

            // 根据获取用户信息
            UserAccount userAccount = userService.findUserAccount(username, Integer.valueOf(identity));

            if (userAccount != null && encoder.matches(password, userAccount.getPassword())) {

                return new MlnxOauthUser(username, password);
            }else{
                throw new LoginException("用户名密码错误");
            }
        }
    }
}
